package evostar.service;

import evostar.model.OrderInfo;
import evostar.model.User;
import evostar.VO.GoodsVO;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class SeckillService {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisService redisService;
    private static final String PATH = "path_";
    public static final String ACCESS = "access_";//access_userId

    @Transactional
    public OrderInfo seckill(User user, GoodsVO goods) {
        //减库存
        if (goodsService.reduceStock(goods) != 0) {
            //创建order订单
            return orderService.createOrder(user, goods);
        } else {
            this.setGoodsOver(goods.getId());
        }
        return null;
    }

    public void setGoodsOver(int goodsId) {
        redisService.setValue(GoodsService.GoodsOver + goodsId, true, 0);
    }

    public Boolean getGoodsOver(int goodsId) {
        return redisService.getValue(GoodsService.GoodsOver + goodsId, Boolean.class);
    }

    public int getSeckillResult(int userId, int goodsId) {
        OrderInfo order = orderService.getSeckillOrderByUserIdGoodsId(userId, goodsId);
        if (order != null) {
            return order.getId();
        } else {
            Boolean over = this.getGoodsOver(goodsId);
            if ((over != null) && over) {
                return -1;
            } else {
                return 0;
            }
        }
    }


    public String createPath(int userId, int goodsId) {
        String path = DigestUtils.md5Hex(UUID.randomUUID().toString() + userId + goodsId);
        redisService.setValue(PATH + userId + "_" + goodsId, path, 60);
        return path;
    }

    public Boolean verifyPath(String path, int userId, int goodsId) {
        String redisPath = redisService.getValue(PATH + userId + "_" + goodsId, String.class);
        return redisPath.equals(path);
    }

}
